﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using Common.Model;
using Common.PddApi;
using Dapper.Contrib.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using pinduoduo.Model;
using pinduoduo.Service;
using pinduoduo.Util;
using Sunny.UI;
using pinduoduo.Global;
using Tk.Soc.Share.Common.Helpers;
using pinduoduo.From;
using Utils;

namespace pinduoduo.Page
{
    public partial class MainPage : UIPage
    {
        private string activityID;
        public PddToken AccountPddToken { get; set; }
        public RequestContext AccountContext { get; set; }
        //private BindingSource bs = new BindingSource();
        private List<ListItem> skuIdList = new List<ListItem>();
        private IEnumerable<AreaModel> areaModelList = new List<AreaModel>();

        private readonly string pddurl = "http://yangkeduo.com/";

        private List<string> gIdList = new List<string>();
        private double CurServerTime = SystemUtil.GetTimeStamp();
        private IList<PddToken> pddTokens = new List<PddToken>();

        private PddTokenService pddTokenService = new PddTokenService();
        //private Dictionary<double, string> kvDictonary = new Dictionary<double, string>();
        private IEnumerable<PddAddressDBModel> pddAddressDBModelList = new List<PddAddressDBModel>();

        private Main mainForm;

        private bool StartTask = false;

        public MainPage(Main mainForm)
        {
            this.mainForm = mainForm;

            InitializeComponent();

            InitUserDataGridView();

            InitGoodIdData();

            InitToken();

            pddAddressDBModelList = DataBaseHelper.SqLiteDBCon.GetAll<PddAddressDBModel>();
            areaModelList = DataBaseHelper.SqLiteDBCon.GetAll<AreaModel>();

            uiToolTip1.SetToolTip(uiSymbolLabel1, "自动支付是模拟鼠标键盘输入\n自动执行过程中请不要操作电脑\n如果不想自动输入密码可不填哦\n如果检测失败，请手动关闭窗口，任务继续进行",
    "自动支付说明", 61530, 32, UIColor.Green);


            string path = AppDomain.CurrentDomain.BaseDirectory + "tmp\\pay.tmp";
            if (File.Exists(path))
            {
                this.PayPassword.Text = File.ReadAllText(path);
                Global.Global.PayPassword = this.PayPassword.Text;
            }

            InitConfig();
        }

        public void UpdateAddressList()
        {
            pddAddressDBModelList = DataBaseHelper.SqLiteDBCon.GetAll<PddAddressDBModel>();
        }

        private void InitConfig()
        {
            string dailiUrl = IniHelper.GetPrivateProfileString("STARTUP", "dailiUrl", IniHelper.IniPathFile, 500);
            string isSetDaili = IniHelper.GetPrivateProfileString("STARTUP", "isSetDaili", IniHelper.IniPathFile, 500);
            string PayModeStr = IniHelper.GetPrivateProfileString("STARTUP", "PayMode", IniHelper.IniPathFile, 500);

            this.GetIpUrl.Text = dailiUrl;

            bool paymode;
            bool.TryParse(PayModeStr, out paymode);
            this.qudongPayCheckBox.Checked = paymode;

            if (isSetDaili == "true")
            {
                this.yuiipRadioButton.Checked = false;
            }
            else
            {
                this.yuiipRadioButton.Checked = true;
            }
        }

        async void InitToken()
        {
            AccountContext = CefUtils.GetAccountContext();
            await CefUtils.GetAccountContext().GetCookieManager(null).FlushStoreAsync();

            List<CefSharp.Cookie> cookies2 = await AccountContext.GetCookieManager(null).VisitUrlCookiesAsync("http://mobile.yangkeduo.com", true);
            List<CefSharp.Cookie> cookies = await AccountContext.GetCookieManager(null).VisitAllCookiesAsync();
            if (cookies == null || cookies.Count == 0)
            {
                //ShowErrorDialog("请先登录账号");
                if(ShowAskDialog("请先登录拼多多大号， 大号主要是获取商品信息的"))
                {
                    mainForm.SelectPage(1);
                }
                return;
            }

            CefSharp.Cookie PDDAccessTokenCookie = cookies.Where(x => { return x.Name == "PDDAccessToken"; }).FirstOrDefault();
            CefSharp.Cookie pdd_user_id_cookie = cookies.Where(x => { return x.Name == "pdd_user_id"; }).FirstOrDefault();
            if (PDDAccessTokenCookie == null || pdd_user_id_cookie == null)
            {
                if (ShowAskDialog("请先登录拼多多大号， 大号主要是获取商品信息的"))
                {
                    mainForm.SelectPage(1);
                }
                return;
            }
            PddToken pddToken = new PddToken();
            pddToken.PDDAccessToken = PDDAccessTokenCookie.Value;
            pddToken.pdd_user_id = pdd_user_id_cookie.Value;
            pddToken.account_type = 1;

            AccountPddToken = pddToken;
        }

        private void InitGoodIdData()
        {
            //var pddGoods = DataBaseHelper.SqLiteDBCon.GetAll<PddGood>();

            //foreach (var item in pddGoods)
            //{
            //    this.GoodComboBox.Items.Add(item.good_id);
            //}
        }
      
        /// <summary>
        /// 初始化UserDataGridView
        /// </summary>
        private void InitUserDataGridView()
        {
            UserDataGridView.AddCheckBoxColumn("选择", "IsCheck").SetFixedMode(50);
            UserDataGridView.AddColumn("序号", "num").SetFixedMode(50);
            UserDataGridView.AddColumn("用户ID", "pdd_user_id").SetFixedMode(130);
            UserDataGridView.AddColumn("最近订单", "last_order_sn");
            UserDataGridView.AddColumn("状态", "status").SetFixedMode(50);
            UserDataGridView.AutoGenerateColumns = false;
            UserDataGridView.ReadOnly = true;
            var tokens = pddTokenService.GetShuaDanToken();
            UserDataGridViewPagination.DataSource = tokens;
            UserDataGridViewPagination.ActivePage = 1;
        }

        private void UserDataGridViewPagination_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            UserDataGridView.DataSource = pagingSource;
        }


        public async Task<bool> GetNetGoodInfoByGoodId(string goodId) 
        {
          
            var response = await PddApi.GetGoodInfo(goodId, AccountPddToken);

            if (string.IsNullOrWhiteSpace(response.Content))
            {
                ShowErrorDialog("获取数据为空！接口有问题啦");
                return false;
            }

            if (response.Content.Contains("请登录后再操作"))
            {
                ShowErrorDialog("请登录后再操作");
                return false;
            }

            if (response.Content.Contains("verify_auth_token")
               && response.Content.Contains("error_code"))
            {
                ShowErrorDialog("请去主账号里输入验证码");
                return false;
            }

            if (response.Content.Contains("verify_auth_token")
              && response.Content.Contains("error_code"))
            {
                ShowErrorDialog("请输入验证码");
                return false;
            }

            if (response.StatusCode != HttpStatusCode.OK)
            {
                ShowErrorDialog("获取失败，请检查主号是否有异常");
                return false;
            }

            var goodInfo = PddApi.PaserGoogInfo(response, goodId);
            if (goodInfo != null) 
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 从网络抓取数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void GetNetGoodButton_Click(object sender, EventArgs e)
        {
            if (AccountPddToken == null)
            {

                ShowErrorDialog("请先登陆主账号");
                return;
            }
            string goodIds = this.GoodIdListTextBox.Text;

            var goodIdList = goodIds.Split(",");

            if (goodIdList.Length == 0)
            {
                ShowErrorDialog("请输入产品ID",true);
                return;
            }

            if (this.PiFaRadioButton.Checked)
            {
               
                string url = "https://pifa.pinduoduo.com/goods/detail/?gid=" + goodIdList[0];
                BrowserFrom browserFrom = new BrowserFrom();
                browserFrom.action = UpdateGoodInfo;
                browserFrom.LoadUrl(url, 5000);
                browserFrom.ShowDialog();

                return;
            }
            if (this.DuoDuoRadioButton.Checked)
            {
                if (goodIdList[0].StartsWith("https://p.pinduoduo.com/"))
                {
                    string url = goodIdList[0];

                    BrowserFrom browserFrom = new BrowserFrom();
                    browserFrom.action = UpdateGoodInfo;
                    browserFrom.SetGoodIdAction = SetGoodId;
                    browserFrom.LoadUrl(url, 5000, (int)PddGoodSource.DuoDuo);
                    browserFrom.ShowDialog();

                    return;
                }
                else
                {
                    ShowErrorDialog("请输入多多链接");
                    return;
                }
            }


            foreach (var goodId in goodIdList)
            {
                if (string.IsNullOrWhiteSpace(goodId)) { continue; }

                var reslut = await  GetNetGoodInfoByGoodId(goodId);
                await Task.Delay(1000);
                if (reslut)
                {
                    Msg("产品id：" + goodId + "数据获取成功");
                }
                else 
                {
                    Msg("产品id：" + goodId + "数据获取失败",true);
                }
            }
            //var response = await PddApi.GetGoodInfo(this.GoodComboBox.Text.Trim(), AccountPddToken);

            //if (string.IsNullOrWhiteSpace(response.Content))
            //{
            //    ShowErrorDialog("获取数据为空！接口有问题啦");
            //    return;
            //}

            //if (response.Content.Contains("请登录后再操作"))
            //{
            //    ShowErrorDialog("请登录后再操作");
            //    return;
            //}

            //if (response.Content.Contains("verify_auth_token")
            //   && response.Content.Contains("error_code"))
            //{
            //    ShowErrorDialog("请去主账号里输入验证码");
            //    return;
            //}

            //if (response.Content.Contains("verify_auth_token")
            //  && response.Content.Contains("error_code"))
            //{
            //    ShowErrorDialog("请输入验证码");
            //    return;
            //}

            //if (response.StatusCode != HttpStatusCode.OK)
            //{
            //    ShowErrorDialog("获取失败，请检查主号是否有异常");
            //    return;
            //}

            //PddGood pddGood = PddApi.PaserGoogInfo(response, this.GoodComboBox.Text.Trim());

            if (goodIdList.Length > 0) 
            {
                PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(goodIdList[0]);
                if (pdd != null) 
                {
                    SetGoodInfo(pdd);
                    this.SourceTextBox.Text = pdd.SourceKeywords;
                }
   
            }

   
        }

        /// <summary>
        /// 从本地抓取数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetDbButton_Click(object sender, EventArgs e)
        {

            string goodIds = this.GoodIdListTextBox.Text;

            var goodIdList = goodIds.Split(",");

            if (goodIdList.Length == 0)
            {
                ShowErrorDialog("请输入产品ID", true);
                return;
            }

            PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(goodIdList[0]);
            if (pdd != null)
            {
                SetGoodInfo(pdd);
                this.SourceTextBox.Text = pdd.SourceKeywords;
            }
        }

        private void SetGoodInfo(PddGood pdd)
        {
            if (pdd == null)
            {
                ShowErrorDialog("请先本地获取！");
                return;
            }

            if (pdd.type == (int)PddGoodSource.DuoDuo)
            {

                dynamic arrdata = JArray.Parse(pdd.sku);

                this.skuIdList.Clear();
                gIdList.Clear();
                gIdList.Add(pdd.gID2);
                gIdList.Add(pdd.gID1);
                activityID = pdd.atvid;
                foreach (dynamic item in arrdata)
                {
                    double skuId = item.skuID;
                    string normalPriceStr = item.normalPrice;
                    string groupPriceStr = item.groupPrice;
                    dynamic specs = item.specs;
                    //    double goodsId = item.goodsId;
                    string spec_value = "";
                    foreach (dynamic spec in specs)
                    {
                        spec_value = spec.spec_value;
                    }

                    try
                    {
                        //string groupPrice = Math.Round((decimal)(Convert.ToDouble(groupPriceStr) / Convert.ToDouble(100)), 2).ToString() + " 元";
                        //string normalPrice = Math.Round((decimal)(Convert.ToDouble(normalPriceStr) / Convert.ToDouble(100)), 2).ToString() + " 元";
                        string text = "拼单:" + groupPriceStr + " 元" + "批发:" + normalPriceStr + "元 " + spec_value;
                        skuIdList.Add(new ListItem(skuId, text));
                    }
                    catch { }

                }
            }

            if (pdd.type == (int)PddGoodSource.Pifa)
            {

                dynamic arrdata = JArray.Parse(pdd.sku);
                this.skuIdList.Clear();
                gIdList.Clear();
                activityID = pdd.atvid;

                foreach (dynamic item in arrdata)
                {
                    double skuId = item.skuId;
                    string normalPriceStr = item.wholesalePrice;
                    string groupPriceStr = item.groupPrice;
                    dynamic specs = item.skuSpecs;
                    //double goodsId = item.goodsId;
                    string spec_value = "";
                    foreach (dynamic spec in specs)
                    {
                        spec_value = spec.specValue;
                    }

                    try
                    {
                        string groupPrice = Math.Round((decimal)(Convert.ToDouble(groupPriceStr) / Convert.ToDouble(100)), 2).ToString() + " 元";
                        string normalPrice = Math.Round((decimal)(Convert.ToDouble(normalPriceStr) / Convert.ToDouble(100)), 2).ToString() + " 元";
                        string text = "拼单:" + groupPrice + " 元" + "批发:" + normalPrice + "元 " + spec_value;
                        skuIdList.Add(new ListItem(skuId, text));
                    }
                    catch { }


                }

            }
            //从页面抓取的
            if (pdd.type == 0)
            {
                string sku = pdd.sku;
                //var arrdata = Newtonsoft.Json.Linq.JArray.Parse(sku);
                var skuObj = JsonHelper.DeserializeObject<List<PddPageGood>>(sku);

                this.skuIdList.Clear();
                gIdList.Clear();
                gIdList.Add(pdd.gID2);
                gIdList.Add(pdd.gID1);
                activityID = pdd.atvid;
                foreach (dynamic item in skuObj)
                {
                    double skuId = item.skuId;
                    string normalPrice = item.normalPrice;
                    string groupPrice = item.groupPrice;
                    dynamic specs = item.specs;
                    double goodsId = item.goodsId;

                    string spec_value = "";
                    foreach (dynamic spec in specs)
                    {
                        spec_value = spec.spec_value;
                    }
                    string text = "拼单:" + groupPrice + " 元" + "单买:" + normalPrice + "元 " + spec_value;
                    skuIdList.Add(new ListItem(skuId, text));
                }
            }

            // 通过渲染界面 接口拿的数据
            if (pdd.type == (int)PddGoodSource.PuTong)
            {
                string sku = pdd.sku;

                dynamic arrdata = JArray.Parse(pdd.sku);

                this.skuIdList.Clear();
                gIdList.Clear();
                gIdList.Add(pdd.gID2);
                gIdList.Add(pdd.gID1);
                activityID = pdd.atvid;
                foreach (dynamic item in arrdata)
                {
                    double skuId = item.sku_id;
                    string normalPrice = item.normal_price;
                    string groupPrice = item.group_price;
                    dynamic specs = item.specs;
                    double goodsId = item.goods_id;

                    string spec_value = "";
                    foreach (dynamic spec in specs)
                    {
                        spec_value = spec.spec_value;
                    }
                    string text = "拼单:" + groupPrice.Insert(groupPrice.Length - 2, ".") + " 元" + "单买:" + normalPrice.Insert(normalPrice.Length - 2, ".") + "元 " + spec_value;
                    skuIdList.Add(new ListItem(skuId, text));
                }
            }

            this.SkuComboBox.BeginInvoke(new Action(() =>
            {
                SkuComboBox.DataSource = null;
                SkuComboBox.DisplayMember = "Text";        //显示
                SkuComboBox.ValueMember = "Value";        //值
                SkuComboBox.DataSource = skuIdList;
                if (skuIdList.Count() > 0)
                {
                    SkuComboBox.SelectedIndex = 0;
                }
            }));
        }

        private void SetGoodId(string goodId)
        {
          //  this.GoodComboBox.Text = goodId;
        }

        private void UpdateGoodInfo()
        {
            string goodIds = this.GoodIdListTextBox.Text;

            var goodIdList = goodIds.Split(",");

            if (goodIdList.Length == 0)
            {
                ShowErrorDialog("请输入产品ID", true);
                return;
            }

            PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(goodIdList[0]);
            if (pdd != null)
            {
                SetGoodInfo(pdd);
                this.SourceTextBox.Text = pdd.SourceKeywords;
            }
        }

        private async void StartPayButtonClick(object sender, EventArgs e)
        {
            if (StartTask)
            {
                Msg("请等待任务完成", true);
                return;
            }
          

            string goodIds = this.GoodIdListTextBox.Text;
            var goodIdList = goodIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            if (goodIdList.Length == 0) 
            {
                Msg("请输入产品ID", true);
                return;
            }
            StartTask = true;
            foreach (var goodId in goodIdList)
            {
                if (string.IsNullOrWhiteSpace(goodId)) { continue; }

                int startIndex = this.UserStartIndex.IntValue;
                int taskNum = this.TaskNum.IntValue;
                var tokens = pddTokenService.GetShuaDanToken();
                if (taskNum > tokens.Count() || startIndex > tokens.Count() || startIndex + taskNum - 1 > tokens.Count())
                {
                    ShowErrorDialog("小号太少了，不能完成任务");
                    StartTask = false;
                    return;
                }

                PddToken pddToken = tokens.ElementAt(startIndex - 1);
                if (pddToken == null)
                {
                    ShowErrorDialog("请先选择一个小号");
                    StartTask = false;
                    return;
                }

                PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(goodId);
                if (pdd != null)
                {
                    SetGoodInfo(pdd);
                    this.SourceTextBox.Text = pdd.SourceKeywords;
                }
                else 
                {
                    Msg("请先获取产品SKU", true);
                    continue;
                }

                try
                {
                    await SingBuyGood(pddToken, goodId, skuIdList[0].Value, true);
                    Msg("任务完成");
                }
                catch (Exception e2)
                {

                    LogHelper.Logger.Error("下单错误", e2);
                }
              
            }
         
            StartTask = false;
        }

        public void UpdateOrderSn(PddToken pddTokenDb) 
        {

            foreach (DataGridViewRow dataGridViewRow in this.UserDataGridView.Rows)
            {
                var pddToken = dataGridViewRow.DataBoundItem as PddToken;
                if (pddTokenDb.pdd_user_id== pddToken.pdd_user_id)
                {
                    pddToken.last_order_sn = pddTokenDb.last_order_sn;
                    this.UserDataGridView.Refresh();
                    break;
                }
            }
        }

        private async Task<PayResult> SingBuyGood(PddToken pddToken,string goodId,double skuId,bool singBuy=false)
        {
            if (this.ZhiBoRadioButton.Checked)
            {
                ShowErrorDialog("直播下单功能即将上线");
                return PayResult.No;
            }


            PddGood pddGood = DataBaseHelper.SqLiteDBCon.Get<PddGood>(goodId);
            if (pddGood == null)
            {
                ShowErrorDialog("请先获取商品信息");
                return PayResult.No;
            }

            if (pddGood.SourceKeywords != this.SourceTextBox.Text)
            {
                pddGood.SourceKeywords = this.SourceTextBox.Text;
                await DataBaseHelper.SqLiteDBCon.UpdateAsync(pddGood);
            }
            //double skuIdStr = (double)this.SkuComboBox.SelectedValue;
            double goodsId = double.Parse(goodId);


            if (this.PiFaRadioButton.Checked)
            {
                if (pddGood.type != (int)PddGoodSource.Pifa)
                {
                    ShowErrorDialog("请先获取批发商品信息");
                    return PayResult.No;
                }
                if (pddGood.firstLadderStartValue == 0)
                {
                    ShowErrorDialog("请重新获取商品信息");
                    return PayResult.No;
                }
                if (this.SkuNumberIntegerTextBox.IntValue < pddGood.firstLadderStartValue)
                {
                    ShowErrorDialog(pddGood.firstLadderStartValue + "件起购");
                    return PayResult.No;
                }
            }

            if (this.DuoDuoRadioButton.Checked)
            {
                if (pddGood.type != (int)PddGoodSource.DuoDuo)
                {
                    ShowErrorDialog("请先获取多多商品信息");
                    return PayResult.No;
                }
            }

            if (this.PuTongRadioButton.Checked)
            {
                if (pddGood.type != (int)PddGoodSource.PuTong)
                {
                    ShowErrorDialog("请先获取普通商品信息");
                    return PayResult.No;
                }
            }
            string daili = "";
            for (int i = 0; i < 3; i++)
            {
                if (yuiipRadioButton.Checked)
                {
                    string errorMsg = string.Empty;
                    daili =  G_Api.GetProxyIp(out errorMsg);
                }
                else
                {
                    string GetIpUrl = this.GetIpUrl.Text;
                    if (string.IsNullOrWhiteSpace(GetIpUrl))
                    {
                        ShowErrorDialog("请先添加提取ip的链接");
                        return PayResult.No;
                    }
                    daili = IPProxy.GetProxyIp(GetIpUrl);
                }

                string realIP = await G_Api.CheckIp(daili);
                if (string.IsNullOrWhiteSpace(realIP))
                {
                    LogRichTextBox.AppendText("检测ip无效，重新获取 \r\n");
                    daili = "";
                }
                else
                {
                    break;
                }
            }


            if (string.IsNullOrEmpty(daili))
            {
                return PayResult.No;
            }

            LogRichTextBox.AppendText("使用IP：" + daili + "\r\n");
            if (!string.IsNullOrWhiteSpace(pddToken.PDDAccessToken))
            {
                var pddUserInfo = await PddApi.GetPddMyInfo(pddToken.pdd_user_id, pddToken.PDDAccessToken, daili);

                if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    pddToken.status = "正常";
                }
                else if (pddUserInfo.Content.Contains("error_code"))
                {
                    pddToken.status = "过期";
                }
                else if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    pddToken.status = "未知";
                }
            }
            else
            {
                pddToken.status = "未知";
            }


            if (pddToken.status == "过期" || pddToken.status == "未知")
            {
                Msg("获取用户信息异常，小号可能过期了", true);
                return PayResult.Ignore;
            }

            if (this.LikeCheckBox.Checked)
            {
                await PddApi.FavoriteGood(pddToken, goodId);
            }

            if (this.NickNameCheckBox.Checked)
            {
                string imageBase64 = null;
                imageBase64 = ImageUtil.GetRandomBase64Avatar(AppDomain.CurrentDomain.BaseDirectory + "avatar");

                if (string.IsNullOrWhiteSpace(imageBase64))
                {
                    Msg("获取本地头像失败，不进行更新头像", true);
                }
                else
                {
                    string nickName = RandomName.GetNickName();
                    Msg("修改昵称：" + nickName);
                    bool result = await PddApi.UpdateNickName(pddToken, nickName, daili);
                    if (!result)
                    {
                        Msg("修改昵称失败", true);
                    }

                    var signature = await PddApi.Signature(pddToken, daili);
                    if (string.IsNullOrWhiteSpace(signature))
                    {
                        Msg("头像上传失败,原因：获取上传签名异常", true);
                    }

                    string imageUrl = await PddApi.UploadAvatar(pddToken, signature, imageBase64, daili);

                    result = await PddApi.UpdateAvatar(pddToken, imageUrl, daili);
                    if (!result)
                    {
                        Msg("头像上传失败", true);
                    }
                }
            }

            string addressid = await AddAddress(this.RandomAddressCheckBox.Checked, pddToken, daili);
            if (string.IsNullOrWhiteSpace(addressid))
            {
                Msg("地址设置异常,准备重试一下", true);
                await Task.Delay(300);
                addressid = await AddAddress(this.RandomAddressCheckBox.Checked, pddToken, daili);
                if (string.IsNullOrWhiteSpace(addressid))
                {
                    Msg("地址第2次设置异常,请稍后重试", true);
                }
                return PayResult.Ignore;
            }


            if (this.PiFaRadioButton.Checked)
            {
                Msg("批发入口下单");

                CreateOrderItemListItem createOrderItemListItem = new CreateOrderItemListItem();
                createOrderItemListItem.goodsId = goodsId;
                createOrderItemListItem.skuId = skuId;
                createOrderItemListItem.skuNum = this.SkuNumberIntegerTextBox.IntValue;
                return await PiFa(pddGood, pddToken, createOrderItemListItem, addressid, daili, singBuy);
                //return false;
            }

            PDDOrder pddOrder = new PDDOrder();
            pddOrder.address_id = addressid;
            var goods = new List<Goods>();
            Goods good = new Goods();
            good.sku_id = skuId.ToString();
            good.goods_id = goodsId.ToString();
            good.sku_number = this.SkuNumberIntegerTextBox.IntValue;
            goods.Add(good);
            pddOrder.goods = goods;

            if (this.GroupTypeCombobox.Text == "参团")
            {
                pddOrder.group_id = gIdList[1];
            }
            else if (this.GroupTypeCombobox.Text == "开团")
            {
                if (gIdList.Count == 2)
                {
                    pddOrder.group_id = gIdList[1];
                }
            }
            else if (this.GroupTypeCombobox.Text == "单独购买")
            {
                pddOrder.group_id = gIdList.FirstOrDefault();
            }

            pddOrder.activity_id = activityID;

            if (this.PuTongRadioButton.Checked)
            {
                Msg("普通入口下单");

                return await PuTongOrder(pddToken, pddOrder, daili, singBuy);
            }

            if (this.DuoDuoRadioButton.Checked)
            {
                Msg("多多入口下单");
                return await DuoDuoOrder(pddGood, pddToken, pddOrder, daili, singBuy);
            }
            return PayResult.Ignore;
        }

        public enum PayResult
        {

            OK = 1, //下单成功
            //Abort = 3,
            Ignore = 5,//下单失败 可以继续
            //Yes = 6,
            No = 7 //下单失败 不能继续
        }

        private void Msg(string msg, bool error = false, bool enter = true)
        {
            if (error) this.LogRichTextBox.SelectionColor = Color.Red;

            LogRichTextBox.AppendText(msg);

            if (enter) LogRichTextBox.AppendText("\r\n");

            if (error) this.LogRichTextBox.SelectionColor = Color.Black;
        }

        private async Task<string> AddAddress(bool random, PddToken pddToken, string daili, bool isDelAddress = false)
        {
            string address_id = "";
            PddAddress pddAddress = new PddAddress();
            PddAddressDBModel pddAddressDBModel = new PddAddressDBModel();
            int index;
            while (true)
            {

                Random r = new Random();
                if (pddAddressDBModelList.Count() == 0)
                {
                    ShowErrorDialog("地址库数据为空");
                    return address_id;
                }
                index = r.Next(0, pddAddressDBModelList.Count());
                pddAddressDBModel = pddAddressDBModelList.ToList()[index];

                if (pddAddressDBModel != null)
                {

                    string[] addressArr = pddAddressDBModel.address.Split(' ');
                    if (addressArr.Length != 4)
                    {
                        continue;
                    }

                    var sheng = areaModelList.Where(x =>
                    {
                        return x.region_type == 1 && (x.region_name.Contains(addressArr[0]) || addressArr[0].Contains(x.region_name));
                    }).FirstOrDefault();
                    if (sheng == null)
                    {
                        continue;
                    }

                    var shi = areaModelList.Where(x =>
                    {
                        return x.region_type == 2 && sheng.region_id == x.parent_id && (x.region_name.Contains(addressArr[1]) || addressArr[1].Contains(x.region_name));
                    }).FirstOrDefault();

                    if (shi == null)
                    {
                        continue;
                    }

                    var xian = areaModelList.Where(x =>
                    {
                        return x.region_type == 3 && shi.region_id == x.parent_id && (x.region_name.Contains(addressArr[2]) || addressArr[2].Contains(x.region_name));
                    }).FirstOrDefault();

                    if (xian == null)
                    {
                        continue;
                    }
                    pddAddress.city_id = shi.region_id;
                    pddAddress.district_id = xian.region_id;
                    pddAddress.province_id = sheng.region_id;
                    pddAddress.name = this.NamePrefixTextBox.Text + pddAddressDBModel.name;
                    pddAddress.mobile = pddAddressDBModel.mobile;
                    pddAddress.address = addressArr[3];
                    pddAddress.is_default = "0";
                    break;
                }

            }

            var res = await PddApi.AddAddressNew(pddToken, pddAddress, daili);
            Msg("地址设置：" + pddAddressDBModel.address);
            if (res.StatusCode == HttpStatusCode.OK && !string.IsNullOrWhiteSpace(res.Content))
            {
                dynamic dyn = JsonConvert.DeserializeObject(res.Content);
                address_id = dyn.address_id;

                if (isDelAddress)
                {
                    Msg("自动删除本地地址：" + pddAddressDBModel.address);
                    DataBaseHelper.SqLiteDBCon.Delete(pddAddressDBModel);
                    pddAddressDBModelList.ToList().RemoveAt(index);
                }
                return address_id;
            }
            else 
            {
                LogHelper.Logger.Debug("地址设置异常："+ pddAddressDBModel.address);
                LogHelper.Logger.Debug("地址设置异常："+ res.Content);
            }

            return address_id;

        }


        private async Task<PayResult> PiFa(PddGood pdd, PddToken pddToken, CreateOrderItemListItem createOrderItemListItem, string addressId, string daili, bool singBuy)
        {
            string urlAnti = "https://mms.pinduoduo.com/pifa/goods/singleBuy";
            string ant = FackUtil.GetAnti(null, urlAnti);

            if (string.IsNullOrWhiteSpace(ant))
            {
                Msg("下单签名失败，请在中间切换个网试试看行不", true);
                return PayResult.Ignore;
            }

            var res = await PddPiFaApi.SingleBuy(pddToken, createOrderItemListItem, ant, daili);
            if (res.StatusCode != HttpStatusCode.OK)
            {
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                Msg("批发下单失败", true);
                return PayResult.Ignore;
            }

            var jo = JObject.Parse(res.Content);

            var success = jo["success"].ToString();
            var errorCode = jo["errorCode"].ToString();
            var errorMsg = jo["errorMsg"].ToString();
            if (success.ToLower() != "true")
            {
                if (errorCode == "6000005")
                {
                    ShowErrorDialog(errorMsg);
                    return PayResult.Ignore;
                }
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                Msg("批发下单失败", true);
                return PayResult.Ignore;
            }

            var qrKey = jo["result"]["qrKey"].ToString();

            if (string.IsNullOrWhiteSpace(qrKey))
            {
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                Msg("批发下单失败", true);
                return PayResult.Ignore;
            }
            var curl = jo["result"]["curl"].ToString();

            string html = await PddPiFaApi.GetTransacOrderCouponHtml(pddToken, curl, daili);
            var pifaClientOrderCreate = PaserOrderHtml(html);
            if (pifaClientOrderCreate == null)
            {
                return PayResult.Ignore;
            }
            urlAnti = "https://mobile.yangkeduo.com/proxy/api/api/pifa-client/order/order_create";
            ant = FackUtil.GetAnti(null, urlAnti);

            pifaClientOrderCreate.secret_key = qrKey;
            pifaClientOrderCreate.anti_content = ant;
            pifaClientOrderCreate.page_id = "";
            pifaClientOrderCreate.address_id = double.Parse(addressId);
            res = await PddPiFaApi.PiFaOrderCreate(pddToken, pifaClientOrderCreate, daili);
            if (res.StatusCode != HttpStatusCode.OK)
            {
                Msg("批发下单失败", true);
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
            }

            jo = JObject.Parse(res.Content);

            success = jo["success"].ToString();

            if (success.ToLower() != "true")
            {
                Msg("批发下单失败", true);
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                return PayResult.Ignore;
            }

            var order_sns = jo["result"]["order_sns"].FirstOrDefault()?.ToString();
            var parent_order_sn = jo["result"]["parent_order_sn"].ToString();

            pddToken.last_order_sn = order_sns;
            UpdateOrderSn(pddToken);
            pddTokenService.UpdateToken(pddToken, true);

            Msg("下单成功，订单号：" + parent_order_sn);

            Order order = new Order();
            order.goodsId = createOrderItemListItem.goodsId.ToString();
            order.orderSn = order_sns;
            order.parent_order_sn = parent_order_sn;
            order.uid = pddToken.pdd_user_id;
            order.buyTime = DateTime.Now.ToString();
            order.skuNumber = createOrderItemListItem.skuNum.ToString();
            order.order_type = "批发订单";

            if (this.OnlyPrePayRadioButton.Checked) 
            {
                order.orderState = "未支付";
                await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);
                Msg("先下单后支付模式，任务完成");
                return PayResult.OK;
            }

          
            res = await PddPiFaApi.PiFPrepay(pddToken, parent_order_sn, daili);

            if (res.StatusCode != HttpStatusCode.OK)
            {
                Msg("批发下单失败", true);
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                return PayResult.Ignore;
            }

            Msg("生成支付链接成功");

            jo = JObject.Parse(res.Content);
            var query = jo["query"];
            var total_fee = jo["query"]["total_fee"].ToString();

            var gateway_url = jo["gateway_url"];

            StringBuilder stringBuilder = new StringBuilder();
            foreach (JToken grandChild in query)
            {
                var p = grandChild as JProperty;
                string s = p.Name + ":" + p.Value;
                stringBuilder.Append(p.Name);
                stringBuilder.Append("=");
                stringBuilder.Append(Uri.EscapeDataString(p.Value.ToString()));
                stringBuilder.Append("&");
            }
            stringBuilder.Remove(stringBuilder.Length - 1, 1);
            string url = gateway_url + "?" + stringBuilder.ToString();
            order.pay_url = url;
            order.goodsMoney = double.Parse(total_fee) * 100 + "";
         
            await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);

            int PayStartIntervalTime = this.PayStartIntervalTimeTextBox.IntValue;
            int PayEndIntervalTime = this.PayEndIntervalTimeTextBox.IntValue;

            if (PayStartIntervalTime > 0 && PayEndIntervalTime > 0 && PayEndIntervalTime > PayStartIntervalTime)
            {
                Random r = new Random();
                int IntervalTime = r.Next(PayStartIntervalTime, PayEndIntervalTime);
                Msg("付款间隔" + IntervalTime + "秒");
                await Task.Delay(TimeSpan.FromSeconds(IntervalTime));
            }

            return AutoPay(url, this.PayPassword.Text, !singBuy) ? PayResult.OK : PayResult.Ignore;

        }

        private async Task<PayResult> PuTongOrder(PddToken pddToken, PDDOrder pddOrder, string daili, bool singBuy)
        {
            var OrderResponse = await PddApi.PddOrder(pddToken.pdd_user_id, pddToken.PDDAccessToken, pddOrder, this.SourceTextBox.Text, daili);

            if (OrderResponse.StatusCode == HttpStatusCode.Forbidden)
            {
                LogHelper.Logger.Error("下单失败:" + OrderResponse.Content);
                Msg("下单失败,请重新获取商品数据试试！", true);
                return PayResult.No;
            }

            if (string.IsNullOrWhiteSpace(OrderResponse.Content))
            {
                LogHelper.Logger.Error("下单失败");
                Msg("下单失败,请重新获取商品数据试试！", true);
                return PayResult.No;
            }

            PDDOrderResponse pDDOrderResponse = null;
            try
            {
                pDDOrderResponse = JsonConvert.DeserializeObject<PDDOrderResponse>(OrderResponse.Content);
            }
            catch (Exception e1)
            {
                LogHelper.Logger.Error("下单失败,返回数据解析失败" + OrderResponse.Content, e1);
                Msg("下单失败,请重新获取商品数据试试！", true);
                return PayResult.No;
            }

            Msg("下单成功，订单号：" + pDDOrderResponse.order_sn);

            //this.UserDataGridView.CurrentRow.Cells["最近订单"].Value = pDDOrderResponse.order_sn;
            pddToken.last_order_sn = pDDOrderResponse.order_sn;
            UpdateOrderSn(pddToken);
            this.UserDataGridView.Refresh();
            pddTokenService.UpdateToken(pddToken, true);

            Order order = new Order();
            order.goodsId = pddOrder.goods.FirstOrDefault().goods_id;
            order.orderSn = pDDOrderResponse.order_sn;
            order.uid = pddToken.pdd_user_id;
            order.buyTime = DateTime.Now.ToString();
            order.skuNumber = pddOrder.goods.FirstOrDefault().sku_number.ToString();
            order.skuName = this.SkuComboBox.Text;
            order.pay_url = "";
            order.order_type = "普通订单";
            order.goodsMoney = pDDOrderResponse.order_amount.ToString();

            if (this.OnlyPrePayRadioButton.Checked)
            {
                order.orderState = "未支付";
                await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);
                Msg("先下单后支付模式，任务完成");
                return PayResult.OK;
            }

            PDDOrderPrepay pDDOrderPrepay = new PDDOrderPrepay();
            pDDOrderPrepay.pay_app_id = 9;
            pDDOrderPrepay.version = 3;
            pDDOrderPrepay.order_sn = pDDOrderResponse.order_sn;
            pDDOrderPrepay.return_url = "http://mobile.yangkeduo.com/transac_wappay_callback.html?order_sn=" + pDDOrderResponse.order_sn + "&prepay_type=";
            pDDOrderPrepay.attribute_fields = new Model.Attribute_fields() { paid_times = 0, forbid_contractcode = "1", forbid_pappay = "1" };

            var res = await PddApi.PddOrderPrepay(pddToken, pDDOrderPrepay, daili);

            if (res.StatusCode != HttpStatusCode.OK)
            {
                Msg("下单失败,订单预付失败", true);
                return PayResult.Ignore;
            }

            //订单预付
            PDDOrderPrepayResponse pDDOrderPrepayResponse = null;
            try
            {
                pDDOrderPrepayResponse = JsonConvert.DeserializeObject<PDDOrderPrepayResponse>(res.Content);

            }
            catch (Exception e1)
            {
                LogHelper.Logger.Error("下单失败,订单预付失败", e1);
                Msg("下单失败,订单预付失败", true);
                return PayResult.Ignore;
            }

            Msg("生成支付链接成功");


            string query = GetUriParam(pDDOrderPrepayResponse.query);
            string url = pDDOrderPrepayResponse.gateway_url + "?" + query;
            order.pay_url = url;
            await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);
            await PddApi.DelAddressById(pddToken, pddOrder.address_id, daili);

            int PayStartIntervalTime = this.PayStartIntervalTimeTextBox.IntValue;
            int PayEndIntervalTime = this.PayEndIntervalTimeTextBox.IntValue;

            if (PayStartIntervalTime > 0 && PayEndIntervalTime > 0 && PayEndIntervalTime > PayStartIntervalTime)
            {
                Random r = new Random();
                int IntervalTime = r.Next(PayStartIntervalTime, PayEndIntervalTime);
                Msg("付款间隔" + IntervalTime + "秒");
                await Task.Delay(TimeSpan.FromSeconds(IntervalTime));
            }


            return AutoPay(url, this.PayPassword.Text,!singBuy) ? PayResult.OK : PayResult.Ignore;
        }

        private async Task<PayResult> DuoDuoOrder(PddGood pddGood, PddToken pddToken, PDDOrder pddOrder, string daili, bool singBuy)
        {

            DuoDuoOrder duoDuoOrder = new DuoDuoOrder();
            duoDuoOrder.group_id = pddOrder.group_id;

            duoDuoOrder.goods = new List<GoodsItem>();
            duoDuoOrder.goods.Add(new GoodsItem(pddOrder.goods.FirstOrDefault()));
            duoDuoOrder.address_id = double.Parse(pddOrder.address_id);

            DuoDuoAttribute_fields duoDuoAttribute_Fields = new DuoDuoAttribute_fields();
            duoDuoAttribute_Fields.cps_sign = pddGood.cps_sign;
            duoDuoAttribute_Fields.DUO_DUO_PID = pddGood.duo_duo_pid;
            duoDuoOrder.attribute_fields = duoDuoAttribute_Fields;

            var OrderResponse = await PddApi.PddOrderDuoDuo(pddToken, duoDuoOrder, daili);

            if (OrderResponse.StatusCode == HttpStatusCode.Forbidden)
            {
                LogHelper.Logger.Error("下单失败:" + OrderResponse.Content);
                Msg("下单失败,请重新获取商品数据试试！", true);
                return PayResult.No;

            }

            if (string.IsNullOrWhiteSpace(OrderResponse.Content))
            {
                LogHelper.Logger.Error("下单失败");
                Msg("下单失败,请重新获取商品数据试试！", true);
                return PayResult.No;

            }
            PDDOrderResponse pDDOrderResponse = null;
            try
            {
                pDDOrderResponse = JsonConvert.DeserializeObject<PDDOrderResponse>(OrderResponse.Content);
            }
            catch (Exception e1)
            {
                LogHelper.Logger.Error("下单失败,返回数据解析失败" + OrderResponse.Content, e1);
                Msg("下单失败,返回数据解析失败！", true);
                return PayResult.Ignore;
            }

            Msg("下单成功，订单号：" + pDDOrderResponse.order_sn);
            pddToken.last_order_sn = pDDOrderResponse.order_sn;
            UpdateOrderSn(pddToken);

            pddTokenService.UpdateToken(pddToken, true);

            Order order = new Order();
            order.goodsId = pddOrder.goods.FirstOrDefault().goods_id;
            order.orderSn = pDDOrderResponse.order_sn;
            order.uid = pddToken.pdd_user_id;
            order.buyTime = DateTime.Now.ToString();
            order.skuNumber = pddOrder.goods.FirstOrDefault().sku_number.ToString();
            order.pay_url = "";
            order.order_type = "多多订单";
            order.goodsMoney = pDDOrderResponse.order_amount.ToString();

            if (this.OnlyPrePayRadioButton.Checked)
            {
                order.orderState = "未支付";
                await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);
                Msg("先下单后支付模式，任务完成");
                return PayResult.OK;
            }

            PDDOrderPrepay pDDOrderPrepay = new PDDOrderPrepay();
            pDDOrderPrepay.pay_app_id = 9;
            pDDOrderPrepay.version = 3;
            pDDOrderPrepay.order_sn = pDDOrderResponse.order_sn;
            pDDOrderPrepay.return_url = "http://mobile.yangkeduo.com/transac_wappay_callback.html?order_sn=" + pDDOrderResponse.order_sn + "&prepay_type=";
            pDDOrderPrepay.attribute_fields = new Model.Attribute_fields() { paid_times = 0, forbid_contractcode = "1", forbid_pappay = "1" };

            var res = await PddApi.PddOrderPrepay(pddToken, pDDOrderPrepay, daili);

            if (res.StatusCode != HttpStatusCode.OK)
            {
                Msg("下单失败,订单预付失败！", true);
                return PayResult.Ignore;
            }

            //订单预付
            PDDOrderPrepayResponse pDDOrderPrepayResponse = null;
            try
            {
                pDDOrderPrepayResponse = JsonConvert.DeserializeObject<PDDOrderPrepayResponse>(res.Content);

            }
            catch (Exception e1)
            {
                LogHelper.Logger.Error("下单失败,订单预付失败", e1);
                Msg("下单失败,订单预付失败！", true);
                return PayResult.Ignore;
            }
            Msg("生成支付链接成功");

            string query = GetUriParam(pDDOrderPrepayResponse.query);
            string url = pDDOrderPrepayResponse.gateway_url + "?" + query;
            order.pay_url = url;
            await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);
            await PddApi.DelAddressById(pddToken, pddOrder.address_id, daili);

            int PayStartIntervalTime = this.PayStartIntervalTimeTextBox.IntValue;
            int PayEndIntervalTime = this.PayEndIntervalTimeTextBox.IntValue;
          
            if (PayStartIntervalTime > 0 && PayEndIntervalTime > 0 && PayEndIntervalTime > PayStartIntervalTime) 
            {
                Random r = new Random();
                int IntervalTime = r.Next(PayStartIntervalTime, PayEndIntervalTime);
                Msg("付款间隔"+IntervalTime+"秒");
                await Task.Delay(TimeSpan.FromSeconds(IntervalTime));
            }

            return AutoPay(url, this.PayPassword.Text, !singBuy) ? PayResult.OK : PayResult.Ignore;
        }

        private PifaClientOrderCreate PaserOrderHtml(string html)
        {
            Regex reg = new Regex("window.rawData= (?<key2>.*?)};");
            Match match = reg.Match(html);
            string tempStr = match.Groups["key2"].Value;
            if (string.IsNullOrWhiteSpace(tempStr))
            {
                Msg("解析数据失败", true);
                return null;
            }
            PifaClientOrderCreate pifaClientOrderCreate = new PifaClientOrderCreate();
            pifaClientOrderCreate.sku_vos = new List<Sku_vosItem>();
            Sku_vosItem sku_VosItem = new Sku_vosItem();
            var jo = JObject.Parse(tempStr + " }");
            var goodsListStore = jo["store"]["goodsListStore"]["goodsList"].ToArray();
            var frontEnv = jo["store"]["envStore"]["frontEnv"].ToObject<int>();
            //var addressId = jo["store"]["addressInfoStore"]["addressId"].ToObject<double>();

            var goods = goodsListStore.FirstOrDefault();
            string goods_id = goods["goodsId"].ToString();
            string group_id = goods["groupId"].ToString();
            string sku_id = goods["skuId"].ToString();
            string sku_number = goods["skuNumber"].ToString();

            sku_VosItem.goods_id = double.Parse(goods_id);
            sku_VosItem.group_id = double.Parse(group_id);
            sku_VosItem.sku_id = double.Parse(sku_id);
            sku_VosItem.sku_number = int.Parse(sku_number);
            pifaClientOrderCreate.front_env = frontEnv;
            pifaClientOrderCreate.sku_vos.Add(sku_VosItem);

            return pifaClientOrderCreate;
        }


        /// <summary>
        /// Model对象转换为uri网址参数形式
        /// </summary>
        /// <param name="obj">Model对象</param>
        /// <param name="url">前部分网址</param>
        /// <returns></returns>
        public static string GetUriParam(object obj, string url = "")
        {
            PropertyInfo[] propertis = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            StringBuilder sb = new StringBuilder();
            sb.Append(url);
            //sb.Append("?");
            foreach (var p in propertis)
            {
                var v = p.GetValue(obj, null);
                if (v == null) v = "";

                sb.Append(p.Name);
                sb.Append("=");
                sb.Append(Uri.EscapeDataString(v.ToString()));//将字符串转换为它的转义表示形式，HttpUtility.UrlEncode是小写
                sb.Append("&");
            }
            sb.Remove(sb.Length - 1, 1);

            return sb.ToString();
        }

        private async void UserDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }
            PddToken pddToken = this.UserDataGridView.Rows[e.RowIndex].DataBoundItem as PddToken;

            if (pddToken == null)
            {
                return;
            }

            DataGridViewCheckBoxCell dataGridViewCheckBoxCell = (DataGridViewCheckBoxCell)(this.UserDataGridView.Rows[this.UserDataGridView.CurrentCell.RowIndex].Cells[0]);
            if (Convert.ToBoolean(dataGridViewCheckBoxCell.EditedFormattedValue) == false)
            {
                dataGridViewCheckBoxCell.Value = true;
            }
            else
            {
                dataGridViewCheckBoxCell.Value = false;
            }


            if (!string.IsNullOrWhiteSpace(pddToken.PDDAccessToken))
            {
                var pddUserInfo = await PddApi.GetPddMyInfo(pddToken.pdd_user_id, pddToken.PDDAccessToken);

                if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    pddToken.status = "正常";
                }
                else if (pddUserInfo.Content.Contains("error_code"))
                {
                    pddToken.status = "过期";
                }
                else if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    pddToken.status = "未知";
                }
                pddTokenService.UpdateToken(pddToken, true);
               
            }
            else
            {
                pddToken.status = "未知";
            }
            this.UserDataGridView.Refresh();
        }

        private async void uiButton1_Click(object sender, EventArgs e)
        {
            if (StartTask)
            {
                Msg("请等待任务完成", true);
                return;
            }
            StartTask = true;
            int startIndex = this.UserStartIndex.IntValue;
            int taskNum = this.TaskNum.IntValue;
            var tokens = pddTokenService.GetShuaDanToken();
            if (taskNum > tokens.Count() || startIndex > tokens.Count() || startIndex + taskNum - 1 > tokens.Count())
            {
                ShowErrorDialog("小号太少了，不能完成任务");
                StartTask = false;
                return;
            }

            for (int i = 0; i < taskNum; i++)
            {
                var token = tokens.ElementAt(startIndex - 1);
                Msg("开始第" + (i + 1) + "个任务 使用小号：" + token.pdd_user_id);

                string goodIds = this.GoodIdListTextBox.Text;

                var goodIdList = goodIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                if (goodIdList.Length == 0)
                {
                    Msg("请输入产品ID", true);
                    StartTask = false;
                    return;
                }


                foreach (var goodId in goodIdList)
                {
                    if (string.IsNullOrWhiteSpace(goodId)) { continue; }

                    PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(goodId);
                    if (pdd != null)
                    {
                        SetGoodInfo(pdd);
                        this.SourceTextBox.Text = pdd.SourceKeywords;
                    }
                    else
                    {
                        Msg("请先获取产品SKU", true);
                        continue;
                    }

                    var result = await SingBuyGood(token, goodId, skuIdList[0].Value);

                    if (result == PayResult.No)
                    {
                        Msg("遇到错误任务终止", true);
                        break;
                    }

                    int PayOrderStartIntervalTime = this.PayOrderStartIntervalTimeTextBox.IntValue;
                    int PayOrderEndIntervalTime = this.PayOrderEndIntervalTimeTextBox.IntValue;

                    if (PayOrderStartIntervalTime > 0 && PayOrderEndIntervalTime > 0 && PayOrderEndIntervalTime > PayOrderStartIntervalTime)
                    {
                        Random r = new Random();
                        int IntervalTime = r.Next(PayOrderStartIntervalTime, PayOrderEndIntervalTime);
                        Msg("下单间隔" + IntervalTime + "秒");
                        await Task.Delay(TimeSpan.FromSeconds(IntervalTime));
                    }
                }
            
                startIndex++;
                Msg("第" + (i + 1) + "个任务完成");
            }
            StartTask = false;
        }

        private void uiButton6_Click(object sender, EventArgs e)
        {

        }

        private async void uiButton7_Click(object sender, EventArgs e)
        {


            //string goodId = this.GoodComboBox.Text.Trim();
            //foreach (DataGridViewRow item in this.UserDataGridView.Rows)
            //{

            //    PddToken pddToken = item.DataBoundItem as PddToken;

            //    var pddUserInfo = await PddApi.GetPddMyInfo(pddToken.pdd_user_id, pddToken.PDDAccessToken);

            //    if (string.IsNullOrWhiteSpace(pddUserInfo.Content))
            //    {
            //        //MessageBox.Show("获取用户信息异常，小号可能过期了");
            //        continue;
            //    }
            //    await PddApi.FavoriteGood(pddToken, goodId);

            //    //if (string.IsNullOrWhiteSpace(text))
            //    //{
            //    //    //MessageBox.Show("小号收藏失败");
            //    //}
            //}

            ShowSuccessDialog("全部收藏完成");
        }

        private void uiButton3_Click(object sender, EventArgs e)
        {
            //调用系统默认的浏览器
            System.Diagnostics.Process.Start("http://www.pdd88.top");
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.txt)|*.txt";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string file = dialog.FileName;
                string text = File.ReadAllText(file);
                if (string.IsNullOrWhiteSpace(text))
                {
                    MessageBox.Show("数据为空");
                    return;
                }
                string[] striparr = text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                var PddTokenList = pddTokenService.GetAllToken();
                foreach (var item in striparr)
                {
                    try
                    {
                        string[] sArray1 = item.Split(new char[4] { '-', '-', '-', '-' }, StringSplitOptions.RemoveEmptyEntries);
                        if (sArray1.Length != 3)
                        {
                            continue;
                        }
                        string qqOrPhone = sArray1[0];
                        string uid = sArray1[1];
                        string token = sArray1[2];
                        PddToken pddToken = new PddToken();
                        pddToken.pdd_user_id = uid;
                        pddToken.PDDAccessToken = token;
                        var pddT = PddTokenList.Where(x =>
                        {
                            return x.pdd_user_id == uid;
                        }).FirstOrDefault();
                        if (pddT != null)
                        {
                            pddToken.id = pddT.id;
                            pddTokenService.UpdateToken(pddToken,true);
                            //DataBaseHelper.SqLiteDBCon.Update<PddToken>(pddToken);
                        }
                        else
                        {
                            pddTokenService.InsertToken(pddToken,true);
                            //var reslut = DataBaseHelper.SqLiteDBCon.Insert<PddToken>(pddToken);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Logger.Error("导入小号失败", ex);
                    }

                }

                var tokens = pddTokenService.GetShuaDanToken();
                UserDataGridViewPagination.DataSource = tokens;
                UserDataGridViewPagination.ActivePage = 1;
            }
        }

        //private void uiButton4_Click(object sender, EventArgs e)
        //{
        //    if (this.UserDataGridView.SelectedRows.Count < 0)
        //    {
        //        return;
        //    }

        //    PddToken pddToken = this.UserDataGridView.CurrentRow.DataBoundItem as PddToken;
        //    if (pddToken == null)
        //    {
        //        return;
        //    }

        //    if (ShowAskDialog("您确定删除吗") )
        //    {

        //        bool reslut = DataBaseHelper.SqLiteDBCon.Delete(pddToken);
        //        if (reslut)
        //        {
        //            //this.UserDataGridView.Rows.Remove(this.UserDataGridView.CurrentRow);
        //            var tokens = pddTokenService.GetAllToken();
        //            UserDataGridViewPagination.DataSource = tokens.Where(x => x.account_type != 1).ToList();
        //        }
        //    }
        //}

        private void uiLabel9_Click(object sender, EventArgs e)
        {

        }

        //private void PayPassword_TextChanged(object sender, EventArgs e)
        //{
        //    browserFrom.ZhiFuPassword = this.PayPassword.Text;
        //}

        private async void uiButton5_Click(object sender, EventArgs e)
        {
            AutoPay("https://mapi.alipay.com/gateway.do?service=alipay.wap.create.direct.pay.by.user&partner=2088911201740274&seller_id=pddzhifubao%40yiran.com&payment_type=1&notify_url=https%3A%2F%2Fpaynotify.pinduoduo.com%2Fnotify%2F9&out_trade_no=XP1121060417200890744164006953&subject=%E5%95%86%E6%88%B7%E5%8D%95%E5%8F%B7XP1121060417200890744164006953&total_fee=14.06&return_url=http%3A%2F%2Fmobile.yangkeduo.com%2Ftransac_wappay_callback.html%3Forder_sn%3D210604-234178530080976%26prepay_type%3D&sign=Mg8qDw%2BJkaz6sU7pn2iRRXjS9i62R%2FalqtIGEr6KUrJud2W%2B7IEA0jVA9LVGxgqa6yGYiMZ%2B%2FrCRiLmtYL7nuRfDlbVTdhFT%2BnLV52tPCIJaEjPTzL%2FQvpGB5Gx45P30RmPm%2Bf3h1N6riOvrDUKXjpjjHcChnbeLQaNur80rdQc%3D&sign_type=RSA&goods_type=1&_input_charset=utf-8&it_b_pay=2021-06-05%2017%3A14", this.PayPassword.Text);
            //  var driver = GetDriver("https://mapi.alipay.com/gateway.do?service=alipay.wap.create.direct.pay.by.user&partner=2088911201740274&seller_id=pddzhifubao%40yiran.com&payment_type=1&notify_url=https%3A%2F%2Fpaynotify.pinduoduo.com%2Fnotify%2F9&out_trade_no=XP1221060415200888338109001531&subject=%E5%95%86%E6%88%B7%E5%8D%95%E5%8F%B7XP1221060415200888338109001531&total_fee=15.96&return_url=http%3A%2F%2Fmobile.yangkeduo.com%2Ftransac_wappay_callback.html%3Forder_sn%3D210604-634435666660517%26prepay_type%3D&sign=XLOdkUgrIYBoYdJQL9%2BynyQL5v5J2c6%2BBRDH1iJioGDGQU5GAd3N2A0qZRsbO5o4O5hexew14fSqAXk%2BR0ERnvFlYdn%2B8iJzntq3rxj4RV75XQ0%2FLW90TTTSLHNEo4g0Elz2CPr9bB3ITiPVRvSRWMtMKUkuZvW36BaOnxNFXWw%3D&sign_type=RSA&goods_type=1&_input_charset=utf-8&it_b_pay=2021-06-05%2015%3A39");
            // var driver = GetDriver("https://mapi.alipay.com/gateway.do?service=alipay.wap.create........................");
            //try
            //{
            //    var zhifuButton = By.XPath("//*[@id=\"cashierPreConfirm\"]/div[2]/button");
            //    driver.FindElement(zhifuButton).Click();
            //    var payInput = By.XPath("//*[@id=\"pwd_unencrypt\"]");
            //    driver.SwitchTo().DefaultContent();
            //    driver.FindElement(payInput).SendKeys("248786");
            //    Thread.Sleep(1000);
            //    string url = driver.Url;
            //    if (url.Contains("https://mclient.alipay.com/h5/cashierPay.htm?awid="))
            //    {
            //        ShowSuccessNotifier("任务成功");
            //        driver.Close();
            //    }
            //    else {
            //        ShowSuccessNotifier("任务失败");
            //    }
            //}
            //catch (Exception)
            //{
            //}

        }

        private void PayPassword_TextChanged(object sender, EventArgs e)
        {
            //string path = AppDomain.CurrentDomain.BaseDirectory + "tmp\\pay.tmp";
            //File.WriteAllText(path, this.PayPassword.Text);
        }

        private void PayPassword_Leave(object sender, EventArgs e)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "tmp\\pay.tmp";
            Global.Global.PayPassword = this.PayPassword.Text;
            File.WriteAllText(path, this.PayPassword.Text);
        }



        private bool AutoPay(string url, string password, bool isClose = false, int timeOut = 5000)
        {

            //BrowserFrom browserFrom = new BrowserFrom(true);
            //browserFrom.AutoPay(url, this.PayPassword.Text, true, timeOut);
            //var res = browserFrom.ShowDialog();


            AutoPayFrom browserFrom = new AutoPayFrom(url, this.PayPassword.Text);
            var res = browserFrom.ShowDialog();

            if (res == DialogResult.OK)
            {
                return true;
            }
            return false;
        }

        private void uiButton5_Click_1(object sender, EventArgs e)
        {
            // AutoPay();
            //string processPath = AppDomain.CurrentDomain.BaseDirectory + "AutoPay.exe";
            //process = Process.Start(processPath, "1");
            //BrowserFrom browserFrom = new BrowserFrom();
            //browserFrom.action = UpdateGoodInfo;
            //browserFrom.LoadUrl("www.baidu.com", 5000);
            //browserFrom.Show();
            //var service = ChromeDriverService.CreateDefaultService();
            //IWebDriver driver = iWebChrome(service);
            //driver.Navigate().GoToUrl("https://fanyi.baidu.com/?aldtype=16047#auto/zh");
            //Thread.Sleep(3000);
            //driver.Navigate().GoToUrl("https://www.baidu.com");
            //Thread.Sleep(3000);
            //driver.Quit();
            //service.Dispose();

            AutoPay("https://mapi.alipay.com/gateway.do?service=alipay.wap.create.direct.pay.by.user&partner=2088911201740274&seller_id=pddzhifubao%40yiran.com&payment_type=1&notify_url=https%3A%2F%2Fpaynotify.pinduoduo.com%2Fnotify%2F9&out_trade_no=XP1221060419201989076476002231&subject=%E5%95%86%E6%88%B7%E5%8D%95%E5%8F%B7XP1221060419201989076476002231&total_fee=16.4&return_url=http%3A%2F%2Fmobile.yangkeduo.com%2Ftransac_wappay_callback.html%3Forder_sn%3D210604-132500706073493%26prepay_type%3D&sign=TKycjMB0ftRWTO9PaiIEZmIlKhy%2BjqTWeZwrnZ9bygvywWfo2GDGMBdd4r%2Fu8uUdUO3CZhqzpMzcAtJBOGwVa65MjDSYrl%2F84GlATGKAtr8EKpDeP%2Be6TUOvEm5Vp2PrejpwSB9LDDuFthmw667X9J%2Bno4WeFQjikoDrNgtRLMM%3D&sign_type=RSA&goods_type=1&_input_charset=utf-8&it_b_pay=2021-06-05%2019%3A46", this.PayPassword.Text);
        }


        public static IWebDriver iWebChrome(ChromeDriverService chromeDriverService)
        {
            ChromeOptions options = new ChromeOptions();
            options.DebuggerAddress = "127.0.0.1:22222";
            chromeDriverService.HideCommandPromptWindow = true;//关闭每次调试时打开的CMD
            IWebDriver driver = new ChromeDriver(chromeDriverService, options, TimeSpan.FromSeconds(10));
            return driver;
        }

        private void UserDataGridView_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.Cells[1].Value = string.Format("{0}", (e.Row.Index + 1) + (this.UserDataGridViewPagination.ActivePage - 1) * UserDataGridViewPagination.PageSize);
        }

        private void UserDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void uiButton5_Click_2(object sender, EventArgs e)
        {
            var pddTokenList = GetSelectRows();
            if (pddTokenList.Count() < 1)
            {
                ShowWarningDialog("请先勾选要删除的数据");
                return;
            }

            if (ShowAskDialog("您确定删除这" + pddTokenList.Count() + "个小号吗?"))
            {
                foreach (var pddToken in pddTokenList)
                {
                    bool reslut = DataBaseHelper.SqLiteDBCon.Delete(pddToken);
                }
                var tokens = pddTokenService.GetShuaDanToken();
                UserDataGridViewPagination.DataSource = tokens;
            }
        }

        public IEnumerable<PddToken> GetSelectRows()
        {
            var pddTokens = new List<PddToken>();
            foreach (DataGridViewRow dataGridViewRow in this.UserDataGridView.Rows)
            {
                var pddToken = dataGridViewRow.DataBoundItem as PddToken;
                if (pddToken.IsCheck)
                {
                    pddTokens.Add(pddToken);
                }
            }
            return pddTokens;
        }

        private void uiCheckBox1_ValueChanged(object sender, bool value)
        {
            foreach (DataGridViewRow dataGridViewRow in this.UserDataGridView.Rows)
            {
                var pddToken = dataGridViewRow.DataBoundItem as PddToken;
                pddToken.IsCheck = uiCheckBox1.Checked;
            }
            this.UserDataGridView.Refresh();
        }

        private void uiButton4_Click(object sender, EventArgs e)
        {
            if (!ShowAskDialog("此模式是测试自动支付驱动是否正常，将进行10次模拟测试，你确定测试吗")) 
            {
                return;   
            }
            for (int i=0;i<10; i++)
            {
                AutoPayFrom browserFrom = new AutoPayFrom("https://wwww.baidu.com", "");
                var res = browserFrom.ShowDialog();
            }
         
        }
       
        private async void uiButton8_Click(object sender, EventArgs e)
        {

            if (!StartTask)
            {
                StartTask = true;
                int PayStartIntervalTime = this.PayStartIntervalTimeTextBox.IntValue;
                int PayEndIntervalTime = this.PayEndIntervalTimeTextBox.IntValue;

                if (PayStartIntervalTime > 0 && PayEndIntervalTime > 0 && PayEndIntervalTime > PayStartIntervalTime)
                {
                    Random r = new Random();
                    int IntervalTime = r.Next(PayStartIntervalTime, PayEndIntervalTime);
                    Msg("付款间隔" + IntervalTime + "秒");
                    await Task.Delay(TimeSpan.FromSeconds(IntervalTime));
                }

                Msg("wanc  秒");
                StartTask = false;
            }
            else 
            {
                Msg("请等待任务完成");
            }
         
        
        }
      

        private void GetIpUrl_TextChanged(object sender, EventArgs e)
        {
            IniHelper.WriteKeyToIni("STARTUP", "dailiUrl", this.GetIpUrl.Text, IniHelper.IniPathFile);
        }

        private void yuiipRadioButton_MouseClick(object sender, MouseEventArgs e)
        {
            IniHelper.WriteKeyToIni("STARTUP", "isSetDaili", "false", IniHelper.IniPathFile);
        }

        private void uiRadioButton1_MouseClick(object sender, MouseEventArgs e)
        {
            IniHelper.WriteKeyToIni("STARTUP", "isSetDaili", "true", IniHelper.IniPathFile);
        }

        private void uiButton8_Click_1(object sender, EventArgs e)
        {
            //AutoPayFrom browserFrom = new AutoPayFrom("https://mapi.alipay.com/gateway.do?service=alipay.wap.create.direct.pay.by.user&partner=2088911201740274&seller_id=pddzhifubao%40yiran.com&payment_type=1&notify_url=https%3A%2F%2Fpaynotify-sh5.pinduoduo.com%2Fnotify%2F9&out_trade_no=XP1121070113500464580528000984&subject=%E5%95%86%E6%88%B7%E5%8D%95%E5%8F%B7XP1121070113500464580528000984&total_fee=11.9&return_url=http%3A%2F%2Fmobile.yangkeduo.com%2Ftransac_wappay_callback.html%3Forder_sn%3D210701-107143496583801%26prepay_type%3D&sign=eK49%2B7hVGGrlY1cyEeGrV4kZgxKbRpbOUTuk2f9wtL7DH6WfbK21pHp9QgvalWDUPblSoVYmVHgsIRJHlZjdyf78gm%2FPsVyceNVJIM2P%2BZpmztl3cvt32%2FGFxKo4%2Bt%2FipLp%2BAmB3bV%2FPWddVVJOrHPduEhnTwE4mMQ46fhyenVc%3D&sign_type=RSA&goods_type=1&_input_charset=utf-8&it_b_pay=2021-07-02%2013%3A24", "123");
            //var res = browserFrom.ShowDialog();
        }

        private void qudongPayCheckBox_MouseClick(object sender, MouseEventArgs e)
        {
            IniHelper.WriteKeyToIni("STARTUP", "PayMode", this.qudongPayCheckBox.Checked.ToString(), IniHelper.IniPathFile);
        }
    }
}
